<?php
namespace App\Http\Controllers\Api;

use App\Models\MShopGood;
use App\Models\MShopOrders;
use App\Models\MUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Mockery\Exception;
use Tests\Models\Image;
use phpqrcode;


/**
 * 佣金
 *
 */
class CommissionController extends ApiController{
    /**
     * 获取佣金推广链接
     *
     */
    public function extension_link(Request $request){
        $goods_id = $request->goods_id??0;
        if (!$goods_id ) {
            return $this->ReturnMessage(-1, '参数有误');
        }
        $user_info = $request->user;
        if ( !$user_info ) {
            return $this->ReturnMessage(-1, '用户信息获取有误');
        }
        $goods_detail = MShopGood::where(['id'=> $goods_id])->first();
        if ( !$goods_detail ) {
            return $this->ReturnMessage(-1, '商品信息获取有误');
        }
        $good_info = $goods_detail ? $goods_detail->toArray(): [];
        // 获取用户的 直推uid 和 间推uid
        $second = DB::table('user_relation')->where(['user_id'=> $user_info->id, 'lay'=> 1])->first();
        $second_info = [];
        if( $second ){
            $second_info = MUser::where(['id'=> $second->pid])->first();
        }

        $basic_url = env('APP_URL') . "/h5/goodsDetails.html?goods_id=".$goods_id;
        $image_name = md5($goods_id.$user_info->id);
        if ( !$second_info ) {
            $params = '&first_uid='.$user_info->id;
        } else {
            $params = '&first_uid='.$user_info->id.'&second_uid='.$second_info->id;
        }
        $link = $basic_url.$params; //二维码内容

        // 生成二维码图片
        $qrc = $this->get_qrcodes($link, $image_name, $goods_detail->background_img);
        if ( !$qrc ){
            $qrc = '';
        }

        return $this->ReturnMessage(200, '获取成功', ["link"=> $link, 'info'=> $good_info, 'qrcode'=> $qrc]);
    }

    /**
     * 获取推广汇总产品列表
     *
     */
    public function get_all_link(Request $request){
        $user_info = $request->user;
        if (!$user_info) {
            return $this->ReturnMessage(-1, '参数有误');
        }
        $h5_index = ((int)$_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . '://'. $_SERVER["HTTP_HOST"] ."/h5";
        $basic_url = $h5_index . "?first_uid=" . $user_info->id;

        $img_info = DB::table("backgroud")->orderBy('id', 'desc')->first();
        $img_background = $img_info? $img_info->value: "";

        // 生成二维码图片
        $qrc = $this->get_qrcodes($basic_url, date("Ymdhis"), $img_background);
        if ( !$qrc ){
            $qrc = '';
        }

        $return_data = [
            "link"   => $basic_url,
            'qrcode' => $qrc,
            'title'  => "推广汇总产品列表",
            'detail' => '生成专属推卡列表，多卡一起推，更快更方便。佣金与单张卡品推广一致哦'
        ];
        return $this->ReturnMessage(200, '获取成功', $return_data);
    }

    /**
     * 获取推广的二维码
     *
     */
    public function get_qrcodes($link, $image_name, $background_img){
        //生成二维码图片
        $object   = new \QRcode();
        $errorCorrectionLevel = 'L';    //容错级别
        $matrixPointSize = 20;
        $root_qrcode= "Public/image/qrcode/";
        if (!is_dir($root_qrcode)) {
            mkdir($root_qrcode,0777,true);
        }
        $fileName = "Public/image/qrcode/".$image_name.'.png';
        //生成图片大小（这个值可以通过参数传进来判断）
        $object->png($link,$fileName,$errorCorrectionLevel, $matrixPointSize, 2);
        if ( !file_exists($background_img) || !file_exists($fileName) ) {
            return false;
        }
        $qrcode = $this->get_background_qrcode($background_img, $fileName, $image_name);
        return $qrcode;
    }

    /**
     * 获取推广二维码
     *
     */
    public function get_qrcode(Request $request){
        $goods_id = $request->goods_id??0;
        $user_id = $request->user_id??0;
        if (!$goods_id || !$user_id) {
            return $this->ReturnMessage(-1, '参数有误');
        }
        $user_info = MUser::where(['id'=> $user_id])->first();
        if ( !$user_info ) {
            return $this->ReturnMessage(-1, '用户信息获取失败');
        }

        $goods_detail = MShopGood::where(['id'=> $goods_id])->first();
        if ( !$goods_detail ) {
            return $this->ReturnMessage(-1, '商品信息获取成功');
        }

        $basic_url = ((int)$_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . '://'.$_SERVER['HTTP_HOST'];
        $image_name = md5($goods_id.$user_id);
        if ( !$user_info->id ) {
            $params = '?first_uid='.$user_info->id.'&goods_id='.$goods_id;
        } else {
            $params = '?first_uid='.$user_info->id.'&second='.$user_info->id.'&goods_id='.$goods_id;
        }
        $link = $basic_url.$params; //二维码内容

        //生成二维码图片
        $qrc = $this->get_qrcodes($link, $image_name, $goods_detail->background_img);
        if ( !$qrc ){
            $qrc = '';
        }

        return $this->ReturnMessage(200, '获取成功', ["qrcode"=> $qrc]);
    }

    /**
     * 对二维码进行拼接
     * @param string $img1  背景图
     * @param string $img2  二维码
     *
     * @return string
     */
    public function get_background_qrcode($img1, $img2, $qrcode_name){
        if (!file_exists($img1)) {
            return false;
        }
        $file_path= "Public/image/extension/";
        if (!is_dir($file_path)) {
            mkdir($file_path,0777,true);
        }
        $image_name = md5('all'.$qrcode_name);
        $fileName = $file_path.$image_name.'.png';
        if ( !file_exists($fileName) ) {
            $img2 = $this->resize($img2, 270, 270);

            //创建图片的实例
            $dst = imagecreatefromstring(file_get_contents($img1));
            $src = imagecreatefromstring(file_get_contents($img2));

            list($dst_w, $dst_h) = getimagesize($img1);

            //获取水印图片的宽高
            list($src_w, $src_h) = getimagesize($img2);
            $dis_h =$dst_h-$src_h;
            $x = ($dst_w-$src_w)/2;
            imagecopymerge($dst, $src, $x, $dis_h-360, 0, 0, $src_w, $src_h, 100);//将二维码放到底图左下角 左边下边各距10像素

            //输出图片
            list($dst_w, $dst_h, $dst_type) = getimagesize($img1);
            imagepng($dst,$fileName);//保存图片
            imagedestroy($dst);
            imagedestroy($src);
        }

        $qrc  = ((int)$_SERVER['SERVER_PORT'] == 443 ? 'https' : 'http') . '://'. $_SERVER["HTTP_HOST"] .'/' . $fileName;
        return $qrc;
    }

    // 定义方法，可用以处理正方形图片或长方形图片尺寸，按宽高比例自适应
    public function resize($imgsrc, $width, $height = 0) {  //参数定义为：源图片，目标宽度，目标高度
        $data = file_get_contents($imgsrc);
        $img_s = imagecreatefromstring($data);  // 获得源图片资源
        $width_s = imagesx($img_s);  // 获得源图片宽度
        $height_s = imagesy($img_s);  // 获得源图片高度

        $width_t = $width;  // 获得目标图片宽度
        $height_t = ($height == 0) ? $width : $height;  // 获得目标图片高度

        $image_t = imagecreatetruecolor($width_t, $height_t); //创建一个彩色的底图
        $white = imagecolorallocate($image_t, 255, 255, 255);
        imagefill($image_t, 0, 0, $white); // 初始化背景为白色

        if (($width_s / $height_s) < ($width_t / $height_t)) {
            $_final['width'] = $width_s * $height_t / $height_s;
            $_final['height'] = $height_t;
            $dst['x'] = ($width_t - $_final['width']) / 2;
            $dst['y'] = 0;
        } else {
            $_final['width'] = $width_t;
            $_final['height'] = $width_t * $height_s / $width_s;
            $dst['x'] = 0;
            $dst['y'] = ($height_t - $_final['height']) / 2;
        }

        ImageCopyResized($image_t, $img_s, $dst['x'], $dst['y'], 0, 0, $_final['width'], $_final['height'], $width_s, $height_s);
        $rel = imagepng($image_t, $imgsrc);
        imagedestroy($img_s);
        imagedestroy($image_t);
        return $rel ? $imgsrc : false;
    }
}
